import axios from 'axios';
import { message } from 'antd';

export interface requestOptions {
  method?: string,
  data?: any,
  pureData?: boolean,
  token?: string,
  timeout?: number
  params?: any
}

export const request = async (url: string, options: requestOptions) => {
  return new Promise<any>((resolve, reject) => {
    const newUrl = process.env.NODE_ENV === 'development' ? `http://localhost:3000/api${url}` : `http://localhost:3000/api${url}`;
    const defaultOptions = {
      method: 'GET',
      pureData: true,
      timeout: 60 * 60 * 1000
    };
    const header = { 'content-type': 'application/json' };
    header['Authorization'] = `Bearer ${options.token || localStorage.getItem('token')}`;
    header['clientType'] = 'web';
    options = Object.assign(defaultOptions, options);
    if (options.method === 'GET') options.params = options.data;
    axios(newUrl, {
      headers: header,
      ...options
    }).then((res) => {
      if (options.pureData) {
        resolve(res.data.data);
        return;
      }
      resolve(res.data);
    }).catch((e) => {
      if (e.response) {
        message.error(e.response.data.desc);
        //reject(e.response.data.desc);
        return;
      }
      message.error('客户端错误');
      reject('客户端错误');
    });
  });
};